package middleware

import (
	"encoding/json"

	"gitee.com/linxing_3/youye-core/sdk/pkg/i18n"
	ginI18n "github.com/gin-contrib/i18n"
	"github.com/gin-gonic/gin"
	"golang.org/x/text/language"
	"gopkg.in/yaml.v3"
)

func I18N(option *i18n.Option) gin.HandlerFunc {

	codecFunc := json.Unmarshal
	switch option.FileType {
	case "yaml", "yml":
		codecFunc = yaml.Unmarshal
	default:
		codecFunc = json.Unmarshal
	}
	return ginI18n.Localize(

		ginI18n.WithGetLngHandle(func(c *gin.Context, defaultLng string) string {
			bindKey := emptyOr(option.BindKey, "accept-language")
			switch option.BindFrom {
			case "header":
				return emptyOr(c.GetHeader(bindKey), defaultLng)
			case "query":
				return emptyOr(c.Query(bindKey), defaultLng)
			default:
				return defaultLng
			}
		}),

		ginI18n.WithBundle(&ginI18n.BundleCfg{
			RootPath:         option.Path,
			AcceptLanguage:   option.GetLngTags(),
			DefaultLanguage:  language.Make(option.DefaultLng),
			UnmarshalFunc:    codecFunc,
			FormatBundleFile: option.FileType,
		}),
	)
}
func emptyOr(v string, or string) string {
	if v == "" {
		return or
	}
	return v
}
